/**
 * Add Favorite
 */

var AddFav = function(accountId, placeId, options){
	this.accountId = accountId;
	this.placeId = placeId;
	this.error = options.error;
	this.success = options.success;
	this.add();
};

AddFav.prototype._success = function(data){
	if(typeof this.success == 'function') {
		this.success(data);
	}
};

AddFav.prototype._error = function(code, message){
	if(typeof this.error == 'function') {
		this.error(code, message);
	}
};

AddFav.prototype.check = function(nextStatement){
	var self = this;
	Mysql.query("SELECT (SELECT COUNT(*) FROM Account WHERE id="+Mysql.escape(self.accountId)+" LIMIT 1) as c1,"
	+"(SELECT COUNT(*) FROM Place WHERE id="+Mysql.escape(self.placeId)+" LIMIT 1) as c2,"
	+"(SELECT COUNT(*) FROM Favorite WHERE AccountId="+Mysql.escape(self.accountId)+" AND placeId="+Mysql.escape(self.placeId)+" LIMIT 1) as c3")
	.on('error', function(error){
		console.log('Mysql error: '+error);
		self._error(9999, 'Mysql error');
	}).on('result', function(result){
		if(result['c1'] == 0) {
			self._error(9999, 'Account Not found');
			return;
		}
		else if(result['c2'] == 0) {
			self._error(9999, 'Place Not found');
			return;
		}
		else if(result['c3'] != 0) {
			self._error(9999, 'Duplicate favorite');
			return;
		}
		nextStatement();
	});
};

AddFav.prototype.add = function(){
	var self = this;
	var accountId = Mysql.escape(self.accountId);
	var placeId = Mysql.escape(self.placeId);
	self.check(function(){
		Mysql.query("INSERT INTO Favorite(accountId, placeId) VALUES("+accountId+","+placeId+")")
		.on('error', function(error){
			console.log('Mysql error: '+error);
			self._error(9999, 'Mysql error');
		})
		.on('result', function(result){
			self._success(result);
		});
	});
};

module.exports = AddFav;